package com.oneToMany.improve.service;

import com.oneToMany.improve.model.Category;
import com.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.util.HashSet;
import java.util.List;

public class BusinessService {

    private HibernateUtil hibernateUtil = new HibernateUtil();
    private SessionFactory sessionFactory = hibernateUtil.getSessionFactory();

    private void saveCategoryWithCascade() {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

            Category foodCategory = new Category("food", new HashSet(), null);
            Category fruitCategory = new Category("fruit", new HashSet(), null);
            Category vegetableCategory = new Category("vegetable", new HashSet(), null);
            Category appleCategory = new Category("apple", new HashSet(), null);
            Category orangeCategory = new Category("orange", new HashSet(), null);
            Category tomatoCategory = new Category("tomato", new HashSet(), null);

            foodCategory.addChildCategory(fruitCategory);

            foodCategory.addChildCategory(vegetableCategory);

            fruitCategory.addChildCategory(appleCategory);

            fruitCategory.addChildCategory(orangeCategory);

            fruitCategory.addChildCategory(tomatoCategory);

            session.save(foodCategory);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
    }

    private void modifyCategoryAssociation() {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Category tomatoCategory = findCategoryByName(session, "tomato");
            Category vegetableCategory = findCategoryByName(session, "vegetable");

            vegetableCategory.addChildCategory(tomatoCategory);

            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
    }

    private Category findCategoryByName(Session session, String name) {
        List results = session.createQuery("from Category as c where c.name='" + name + "'").list();
        return (Category) results.iterator().next();
    }
    private void test() {
        saveCategoryWithCascade();
        modifyCategoryAssociation();
        sessionFactory.close();
    }

    public static void main(String args[]) {
        new BusinessService().test();
    }
}

